class WxRequest{
  // 为不同项目设置相同默认配置参数
  defaults = {
    baseURL: "",
    url: "",
    data: null,
    method: "GET",
    header: {
      "Content-type": "application/json"
    },
    timeout: 60000,
    isLoading: true
  }
  constructor(params = {}){
    // constructor构造函数params形参接收实例化对象传递的参数
    this.defaults = Object.assign({},this.defaults,params)
  }
  // 定义默认请求拦截器、响应拦截器
  interceptor = {
    request: config => config,
    response: response => response
  }
  queue = []
  request (options) {
    this.timerId && clearTimeout(this.timerId)
    // options接收request方法传递的请求参数
    options.url = this.defaults.baseURL + options.url
    options = {...this.defaults,...options}
    if(options.isLoading && options.method !== "UPLOAD"){
      this.queue.length === 0 && wx.showLoading()
      this.queue.push("request")
    }
    // 调用请求拦截器
    options = this.interceptor.request(options)
    return new Promise((resolve,reject)=>{
      if(options.method === "UPLOAD"){
        wx.uploadFile({
          ...options,
          success: (res) => {
            res.data = JSON.parse(res.data)
            const mergeRes = Object.assign({},res,{config:options,isSuccess:true})
            resolve(this.interceptor.response(mergeRes))
          },
          fail: (err) => {
            const mergeErr = Object.assign({},err,{config:options,isSuccess:false})
            reject(this.interceptor.response(mergeErr))
          }
        })
      }
      else {
        wx.request({
          ...options,
          success:(res)=>{
            // 调用响应拦截器
            const mergeRes = Object.assign({},res,{config:options,isSuccess:true})
            resolve(this.interceptor.response(mergeRes))
          },
          fail:(err)=>{
            // 调用响应拦截器
            const mergeErr = Object.assign({},err,{config:options,isSuccess:false})
            reject(this.interceptor.response(mergeErr))
          },
          complete:()=>{
            if(options.isLoading){
              this.queue.pop()
              this.queue.length === 0 && this.queue.push("request")
              this.timerId = setTimeout(()=>{
                this.queue.pop()
                this.queue.length === 0 && wx.hideLoading()
                clearTimeout(this.timerId)
              },1)
            }
          }
        })
      }
    })
  }
  // 定义快捷请求方法
  get(url,data={},config={}){
    return this.request(Object.assign({url,data,method:"GET"},config))
  }
  post(url,data={},config={}){
    return this.request(Object.assign({url,data,method:"POST"},config))
  }
  delete(url,data={},config={}){
    return this.request(Object.assign({url,data,method:"DELETE"},config))
  }
  put(url,data={},config={}){
    return this.request(Object.assign({url,data,method:"PUT"},config))
  }
  all(...promise){
    return Promise.all(promise)
  }
  upLoad(url,filePath,name='file',config={}){
    return this.request(Object.assign({url,filePath,name,method:'UPLOAD'},config))
  }
}
export default WxRequest